var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
let cors = require("cors");
const { expressjwt: expressJwt } = require("express-jwt");
const secret = "your_jwt_secret";

var indexRouter = require("./routes/index");
var usersRouter = require("./routes/users");
var jjxRouter = require("./routes/jjx");
var jjkRouter = require("./routes/jjk");
var ltcRouter = require("./routes/ltc");
var zjxRouter = require("./routes/zjx");
var bkcRouter = require("./routes/bkc");

// 导入聊天室 WebSocket
const attachChatWebSocket = require("./routes/webSocked-chatroom/app");

var app = express();

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");

// 创建HTTP服务器
const server = require("http").createServer(app);

// CORS 配置 - 支持多个前端域名
const allowedOrigins = [
  "http://localhost:5173", // 本地开发
  "http://localhost:3000", // 其他本地端口
  // 'https://4b4c6c55.r9.cpolar.top', // 远程开发环境
  // 'https://6c46076a.r9.cpolar.top', // 原有远程接口环境
  "https://537e7f45.r9.cpolar.top", // HTTPS远程接口
  "https://69f63df3.r9.cpolar.top", // 新的远程接口
  "https://lutiance-1371863414.cos-website.ap-beijing.myqcloud.com", // 生产环境
];

app.use(
  cors({
    origin: function (origin, callback) {
      // 允许没有 origin 的请求（比如同源请求）
      if (!origin) return callback(null, true);

      if (allowedOrigins.indexOf(origin) !== -1) {
        callback(null, true);
      } else {
        console.log("CORS blocked origin:", origin);
        callback(new Error("Not allowed by CORS"));
      }
    },
    credentials: true, // 允许携带cookie
    methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    allowedHeaders: ["Content-Type", "Authorization", "X-Requested-With"],
  })
);

app.use(logger("dev"));
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ extended: false, limit: '50mb' }));
app.use(cookieParser());
app.use(
  expressJwt({
    secret,
    algorithms: ["HS256"],
    getToken: (req) =>
      req.headers.authorization?.split(" ")[1] || req.cookies["access_token"],
  }).unless({
    path: ['/ltc/login', '/ltc/refresh-token', '/ltc/sendcode', '/ltc/createuser', '/ltc/sendcode_login', '/api/jjk/shi', '/api/jjk/zixun',"/jjx/car-data","/jjx/export-csv","/jjx/export-image", /^\/uploads\/.*/, /^\/api\/jjk\/shi\/.*\/like$/, /^\/api\/jjk\/shi\/.*$/]
  })
);
// 根据环境配置静态资源缓存
if (process.env.NODE_ENV === "production") {
  // 生产环境：为静态文件设置长期缓存
  app.use(
    express.static(path.join(__dirname, "public"), {
      maxAge: "1y", // 默认缓存1年
      setHeaders: function (res, path) {
        // 对于HTML文件，设置Cache-Control为no-cache
        if (express.static.mime.lookup(path) === "text/html") {
          res.setHeader("Cache-Control", "public, max-age=0");
        }
      },
    })
  );
} else {
  // 开发环境：不设置强缓存，便于调试
  app.use(express.static(path.join(__dirname, "public")));
}

app.use("/", indexRouter);
app.use("/users", usersRouter);
app.use("/jjx", jjxRouter);
app.use("/api/jjk", jjkRouter);
app.use("/bkc", bkcRouter);
app.use("/zjx", zjxRouter);
app.use("/ltc", ltcRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

// 初始化WebSocket
jjxRouter.initWebSocket(server);
// 初始化聊天室WebSocket
attachChatWebSocket(server);

module.exports = { app, server };
